'use strict'
import axios from 'axios';
import { getToken } from '@/utils/Token';
export default {
    data () {
        return {
            baseUrl: `${process.env.VUE_APP_FILE_URL}/`,
            numberInputPass: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'Backspace'],
            inputPass: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9','Backspace']
        }
    },
    methods: {
        inputReplaceSpecialChar(myString) {
            return myString.replace(/[^\u4e00-\u9fa5\w]/g, '');
        },
        inputNoneNumberUnpass(e) {
            let key = e.key;
            if (this.numberInputPass.includes(key)) {
                return true;
            }
            e.returnValue = false;
            return false;
        },
        inputUnpass(e) {
           let key = e.key;
           var reg = /^[a-zA-Z]+$/
          if (this.inputPass.includes(key) || reg.test(key)) {
           return true;
          }else {
            e.returnValue = false;
           return false;
         }
        },
        inputCode(e) {
            e.key=e.key.replace(/[^a-zA-Z]/g,'')
        },       
        filesDownload(files) {
            if (!files || !files.length) return;
            let triggerDelay = 100;
            let removeDelay = 1000;
            files.forEach((item, index) => {
                if (item.indexOf(this.baseUrl) >= 0) {
                    this.createIFrame(item, index * triggerDelay, removeDelay);
                    return;
                }
                this.createIFrame(this.baseUrl + item, index * triggerDelay, removeDelay);
            })
        },
        createIFrame(url, triggerDelay, removeDelay) {
            //动态添加iframe，设置src，然后删除
            setTimeout(() => {
                const frame = document.createElement('iframe');
                frame.style.display = 'none';
                frame.src = url;
                document.body.append(frame);
                setTimeout(() => {
                    frame.remove();
                }, removeDelay);
            }, triggerDelay);
        },
         blobAxiosApi(method, url, data, fileName) {
            return axios({
                method: method,
                url: url,
                params: method == 'get' ? data : null,
                data: method == 'post' ? data : null,
                responseType: 'blob',
                baseURL: process.env.VUE_APP_BASE_API,
                headers: {
                    Authorization: getToken()
                }
              })
              .then(async (res) => {
                  
                res = await this.judgeErrorByResponseType(res)
                // if(res.status && res.status == 500) {
                //     this.$message.error(res.msg)
                //     return
                //   }else {
                    let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'});
                    let url = window.URL.createObjectURL(blob);
            
                    var elink = document.createElement('a');
                    elink.download = fileName;
                    elink.style.display = 'none';
                    elink.href = url;
            
                    document.body.appendChild(elink);
                    elink.click();
            
                    document.body.removeChild(elink);
                //   }
              })
              .catch(err => {
                this.$message.error(err)
              })
        },
         judgeErrorByResponseType(response) {
            return new Promise((resolve, reject) => {
                console.log(response.headers['content-type'].includes('json'))
              if (response.headers['content-type'].includes('json')) {
                const { data } = response
                const reader = new FileReader()
                reader.onload = () => {
                  const { result } = reader
                  const errorInfos = JSON.parse(result)
                  const { msg } = errorInfos
                reject(msg)
                }
                reader.onerror = err => {
                  reject(err)
                }
                reader.readAsText(data)
              }
              
              else {
                resolve(response)
              }
            })
          },
        autoComplateString(myString, length) {
            let newString = myString ? myString : '';
            if (newString.length < length) {
                const len = length - newString.length;
                newString = (0 / Math.pow(10, len)).toFixed(len).substr(2) + newString;
            }  else if (newString.length > length) {
                return newString.substring(0, length);
            }
            return newString;
        }
    }
}
